package com.as.measurement.sender.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.as.measurements.client.core.models.JperfStreamResult;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

public class Sender extends Thread {

	/**
	 * Logger
	 */
	private Log _logger = LogFactory.getLog(getClass().getName());
	protected static Socket socket;
	static InputStream inputStream;
	static OutputStream outputStream;
	static String hostname = "127.0.0.1";
	static int port = 6969;
	private JperfStreamResult	 _jperfRestult = null;

	public Sender(JperfStreamResult	finalResults) {
		
		_jperfRestult = finalResults;

	}

	public void run() {

		try {
			socket = new Socket(hostname, port);

			socket.setSoTimeout(120000); // 2 minutos
			// get the socket streams
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();

		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		send();

		try {
			outputStream.close();

			inputStream.close();
			socket.close();
			System.out.println("Done");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private int send(){
		ObjectOutputStream oos;
		try{
			oos = new ObjectOutputStream(outputStream);
			oos.writeObject(_jperfRestult);
			oos.flush();
		}
		catch(IOException e){
			e.printStackTrace();
			return -1;
		}
		
//		 wait for the server response 
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
		String response = "";
		try {
			response = in.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (response.equals("accept")) {
			System.out.println("the petition has been accepted by the server");
			
		}
		if (response.equals("Error Corrupted Stream")){
			System.out.println("error corrupted stream");
			return -2;
		}
		else{
			return -1;
		}
		
		
	}
}
